<template>
  <el-card class="box-card">
    <div class="header">
      <el-button type="success" size="medium" icon="el-icon-plus" @click="showCreateDialog">新增菜单</el-button>
    </div>
    <div class="body">
      <el-table
        :data="menuList"
        style="width: 100%"
        row-key="menuId"
        border
        lazy
        :load="loadMenu"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <!-- <el-table-column prop="menuId" label="菜单编号" min-width="250" align="center"></el-table-column> -->
        <el-table-column prop="menuName" label="菜单名称" min-width="250" align="center" />
        <el-table-column prop="menuIcon" label="图标" min-width="250" align="center">
          <template slot-scope="{row}">
            <svg-icon :icon-class="row.menuIcon" />
          </template>
        </el-table-column>
        <el-table-column prop="permissionKey" label="权限标识" width="250" align="center" />
        <el-table-column label="菜单类型" width="250" align="center">
          <template slot-scope="{row}">
            <el-tag type="default">{{ row.menuType | queryMenuTypeFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="menuPath" label="路由地址" min-width="250" align="center" />
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="310px"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{row}">
            <el-button
              type="success"
              icon="el-icon-view"
              size="mini"
              plain
              @click="showViewDialog(row.menuId)"
            >查看
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showUpdateDialog(row.menuId)"
            >编辑
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              plain
              @click="deleteHandle(row.menuId)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :title="titleMap[dialogStatus]"
      :lock-scroll="true"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <!-- 二级选择菜单弹框 -->
      <el-dialog width="30%" title="选择上级菜单" :visible.sync="innerVisible" append-to-body>
        <el-tree :data="treeData" :props="menuTreeProps" @node-click="changeClick" />
      </el-dialog>
      <!-- 二级选择菜单弹框 -->
      <!-- 打开内层图标弹框 -->
      <el-dialog width="50%" title="选择菜单图标" :visible.sync="innerVisible1" append-to-body>
        <ul class="iconUl">
          <li v-for="(ic,key) in icons" :key="key">
            <svg-icon :icon-class="ic.icsrc" @click="iconCheck(ic.icsrc)" />
            <span>{{ ic.icsrc }}</span>
          </li>
        </ul>
      </el-dialog>
      <!-- 打开内层图标弹框 -->
      <!-- 一级添加菜单 -->
      <div class="dialogBody">
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <el-form
            ref="form"
            :model="form"
            label-width="110px"
            :disabled="!(dialogStatus ==='update' || dialogStatus ==='create')"
          >
            <el-row>
              <el-col :xs="24" :md="24">
                <el-form-item
                  label="菜单名称"
                  prop="menuName"
                  :rules="[
                    { required: true, message: '菜单名称不能为空'}
                  ]"
                >
                  <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="24">
                <el-form-item label="上级菜单">
                  <el-input
                    v-model="form.parentName"
                    type="text"
                    :readonly="true"
                    placeholder="请输入上级菜单"
                  >
                    <el-button slot="append" @click="innerVisible = true">选择</el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="24">
                <el-form-item label="路由地址" prop="menuPath">
                  <el-input v-model="form.menuPath" placeholder="请输入路由地址" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="24">
                <el-form-item
                  label="权限标识"
                  prop="permissionKey"
                  :rules="[
                    { required: true, message: '权限标识不能为空'}
                  ]"
                >
                  <el-input v-model="form.permissionKey" type="text" placeholder="权限标识" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="24">
                <el-form-item label="组件名称" prop="component">
                  <el-input v-model="form.component" type="text" placeholder="组件名称" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="24">
                <el-form-item label="菜单类型">
                  <el-select v-model="form.menuType" size="medium" placeholder="菜单类型">
                    <el-option
                      v-for="(mt,key) in menuTypeOptions"
                      :key="key"
                      :label="mt.name"
                      :value="mt.value"
                    />
                  </el-select>
                  <span>注意：二级菜单不需要添加图标。</span>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="24">
                <el-form-item label="图标">
                  <el-input v-model="form.menuIcon" />
                  <span class="checkicon">
                    <a href="javascript:;" @click="innerVisible1 = true">选择图标</a>&nbsp;&nbsp;例:
                    <svg-icon icon-class="dashboard" />
                    <span>dashboard</span>
                  </span>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="24">
                <el-form-item label="外链地址">
                  <el-input v-model="form.redirectUrl" placeholder="外链地址" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="24">
                <el-form-item label="菜单说明">
                  <el-input v-model="form.remake" placeholder="附加说明" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="24">
                <el-form-item label="菜单排序">
                  <el-input v-model="form.sortId" type="number" placeholder="菜单排序" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-scrollbar>
      </div>
      <!-- 一级添加菜单 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus ==='update' || dialogStatus ==='create' "
          type="primary"
          @click="saveHandle"
        >保存
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
import {
  treeList,
  list,
  findById,
  save,
  deleteById,
  updateById
} from '@/api/menu'
import { getData } from '@/api/dict'

let that
export default {
  name: 'Menu',
  inject: ['reload'],
  filters: {
    queryPositionTypeFilter(key) {
      let typeName = ''
      console.log(that)
      that.menuTypeOptions.forEach((e) => {
        if (e.value === key) {
          typeName = e.name
        }
      })
      return typeName
    },
    queryMenuTypeFilter(key) {
      let typeName = ''
      that.menuTypeOptions.forEach((e) => {
        if (e.value === key) {
          typeName = e.name
        }
      })
      return typeName
    }
  },
  data() {
    return {
      menuTypeOptions: [],
      icons: [
        { icsrc: 'dashboard' },
        { icsrc: 'education' },
        { icsrc: 'email' },
        { icsrc: 'example' },
        { icsrc: 'excel' },
        { icsrc: 'exit-fullscreen' },
        { icsrc: 'eye' },
        { icsrc: 'eye-open' },
        { icsrc: 'form' },
        { icsrc: 'fullscreen' },
        { icsrc: 'guide' },
        { icsrc: 'icon' },
        { icsrc: 'international' },
        { icsrc: 'language' },
        { icsrc: 'layer-group-fill' },
        { icsrc: 'link' },
        { icsrc: 'list' },
        { icsrc: 'lock' },
        { icsrc: 'message' },
        { icsrc: 'money' },
        { icsrc: 'nested' },
        { icsrc: 'paper-plane-fill' },
        { icsrc: 'password' },
        { icsrc: 'pdf' },
        { icsrc: 'people' },
        { icsrc: 'peoples' },
        { icsrc: 'qq' },
        { icsrc: 'search' },
        { icsrc: 'setting' },
        { icsrc: 'shopping' },
        { icsrc: 'size' },
        { icsrc: 'skill' },
        { icsrc: 'star' },
        { icsrc: 'tab' },
        { icsrc: 'table' },
        { icsrc: 'theme' },
        { icsrc: 'tree' },
        { icsrc: 'tree-table' },
        { icsrc: 'user' },
        { icsrc: 'user-plus-fill' },
        { icsrc: 'wechat' },
        { icsrc: 'zip' }
      ],
      treeData: [],
      dialogFormVisible: false,
      innerVisible: false,
      innerVisible1: false,
      form: {
        menuName: '',
        parentName: '',
        menuPath: '',
        permissionKey: '',
        component: '',
        menuType: '',
        menuIcon: '',
        redirectUrl: '',
        remake: '',
        sortId: ''
      },
      titleMap: {
        update: '编辑菜单',
        create: '新建菜单',
        view: '查看菜单'
      },

      listQuery: {
        parentId: undefined
      },
      dialogStatus: '',
      menuList: [],
      menuTreeProps: {
        label: 'menuName',
        children: 'children'
      }
    }
  },
  beforeCreate: function() {
    that = this
  },
  created() {
    // 页面加载的时候执行
    this.getList()
    this.getTreeList()
    this.getDictData()
  },
  methods: {
    getDictData() {
      getData('menuType').then((res) => {
        that.menuTypeOptions = res.data
      })
    },
    // 图标选择
    iconCheck(res) {
      this.innerVisible1 = false
      console.log(res)
      this.form.menuIcon = res
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ menuId: '0', menuName: '根目录' }])
      }
      treeList({
        parentId: node.key
      }).then((response) => {
        const data = response.data
        resolve(data)
      })
    },
    loadMenu(tree, treeNode, resolve) {
      list({
        parentId: tree.menuId
      }).then((response) => {
        const data = response.data
        resolve(data)
      })
    },
    getList() {
      this.listLoading = true
      treeList(this.listQuery).then((response) => {
        this.menuList = response.data
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    showCreateDialog() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.form = {}
    },
    showViewDialog(id) {
      this.resetForm()
      this.dialogStatus = 'view'
      findById(id).then((response) => {
        this.form = response.data
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
      this.dialogFormVisible = true
    },
    showUpdateDialog(id) {
      this.resetForm()
      this.dialogStatus = 'update'
      findById(id).then((response) => {
        this.form = response.data
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
      this.dialogFormVisible = true
    },
    deleteHandle(id) {
      this.$confirm('是否删除这条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(id).then(() => {
          this.reload()
        })
      })
    },
    // 点击按钮添加菜单
    saveHandle() {
      const me = this
      me.$refs.form.validate((valid) => {
        if (valid) {
          // this.downloadLoading = true;
          if (me.dialogStatus === 'create') {
            save(this.form).then(() => {
              this.listLoading = false
              me.dialogFormVisible = false
              this.reload()
            })
          } else {
            updateById(this.form).then(() => {
              this.listLoading = false
              me.dialogFormVisible = false
              this.reload()
            })
          }
        } else {
          return false
        }
      })
    },
    resetForm() {
      if (this.$refs.form !== undefined) {
        // 重置表单
        this.$refs.form.resetFields()
      }
    },
    changeClick(obj, node, data) {
      this.form.parentId = obj.menuId
      this.form.parentName = obj.menuName
      this.innerVisible = false
    },

    // 选择上级菜单的树形获取数据
    getTreeList() {
      treeList().then((response) => {
        this.treeData = response.data
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {
        })
    }
  }
}
</script>
<style lang="scss" scoped>
/* 图标样式 */
.iconUl {
  list-style: none;
  margin: 0;
  padding: 0;
}

.iconUl li {
  float: left;
  padding: 0 15px;
  text-align: center;
  width: 25%;
  margin-bottom: 20px;
  cursor: pointer;
}

.iconUl li span {
  line-height: 28px;
  display: block;
}

.iconUl li .svg-icon {
  color: #606266;
  font-size: 32px;
}

.el-dialog__body {
  overflow: hidden;
}

/* 图标样式 */
.box-card {
  height: 100%;
  margin: 10px 8px;
  padding: 0;
}

.header {
  margin-bottom: 10px;
}

.dialogBody {
  height: 400px;
  overflow: hidden;
}

.scrollbar-wrapper {
  overflow-x: hidden !important;
}

.el-scrollbar__bar.is-vertical {
  right: 0px;
}

.el-scrollbar {
  height: 100%;
}

.checkicon a {
  color: #1890ff;
}

.checkicon a:hover {
  color: #1890ff;
}

.checkicon svg {
  margin: 0 6px 0 10px;
}
</style>

